package com.vipyinzhiwei.android.sample;

import android.content.Context;
import android.os.Build;
import android.text.TextUtils;

import com.bumptech.glide.Glide;
import com.bumptech.glide.integration.okhttp3.OkHttpUrlLoader;
import com.bumptech.glide.load.model.GlideUrl;
import com.franmontiel.persistentcookiejar.PersistentCookieJar;
import com.franmontiel.persistentcookiejar.cache.SetCookieCache;
import com.franmontiel.persistentcookiejar.persistence.SharedPrefsCookiePersistor;
import com.vipyinzhiwei.android.BuildConfig;
import com.vipyinzhiwei.android.GlobalApplication;
import com.vipyinzhiwei.android.library.network.okhttp.OkHttpUtils;

import java.io.IOException;
import java.io.InputStream;
import java.util.concurrent.TimeUnit;

import okhttp3.CookieJar;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
import retrofit2.converter.scalars.ScalarsConverterFactory;

/**
 * 网络通信配置帮助类
 *
 * @author vipyinzhiwei
 * @version 1.0
 */
public class ApiHelper {
    private static Api mApi;
    private static String userAgent;

    public static Api api() {
        if (mApi == null)
            initNetworkConfig();
        return mApi;
    }

    /**
     * 初始化网络配置相关
     */
    public static void initNetworkConfig() {
        //初始化okhttp
        OkHttpClient okHttpClient = initOkHttpClient();
        //初始化Retrofit-api
        mApi = getRetrofitApi(okHttpClient, Api.class);
        //配置Glide网络层使用Okhttp3
        Glide.get(GlobalApplication.gainContext()).getRegistry().replace(GlideUrl.class, InputStream.class, new OkHttpUrlLoader.Factory(okHttpClient));
        //绑定OkHttpUtils工具类
        OkHttpUtils.initClient(okHttpClient);
    }

    /**
     * 初始化网络相关配置OkHttpClient
     */
    public static OkHttpClient initOkHttpClient() {
        OkHttpClient okHttpClient = new OkHttpClient().newBuilder()
                .addInterceptor(getHeaderInterceptor())
                .addInterceptor(getLogInterceptor())
                .cookieJar(getCookieJar(GlobalApplication.gainContext()))
                .readTimeout(10, TimeUnit.SECONDS)
                .writeTimeout(20, TimeUnit.SECONDS)
                .connectTimeout(10, TimeUnit.SECONDS)
                .build();

        return okHttpClient;
    }

    /**
     * 初始化网络相关配置OkHttpClient
     */
    public static Retrofit initRetrofit(OkHttpClient okHttpClient) {
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(BuildConfig.API_HOST)
                .addConverterFactory(ScalarsConverterFactory.create())
                .addConverterFactory(GsonConverterFactory.create())
                .client(okHttpClient)
                .build();

        return retrofit;
    }

    /**
     * 获取Api接口
     */
    public static <T> T getRetrofitApi(OkHttpClient okHttpClient, final Class<T> service) {
        return initRetrofit(okHttpClient).create(service);
    }

    /**
     * 获取自定义配置Header拦截器
     *
     * @return
     */
    private static Interceptor getHeaderInterceptor() {
        Interceptor headerInter = new Interceptor() {
            @Override
            public okhttp3.Response intercept(Chain chain) throws IOException {
                Request newRequest = chain.request()
                        .newBuilder()
                        .addHeader("platform", "android")
                        .addHeader("device-id", "")
                        .addHeader("version", BuildConfig.VERSION_NAME)
                        .addHeader("channel", BuildConfig.APPLICATION_ID)
                        .addHeader("User-Agent", TextUtils.isEmpty(userAgent) ? getUserAgent() : userAgent)
                        .build();
                okhttp3.Response response = chain.proceed(newRequest);
                return response;
            }
        };
        return headerInter;
    }

    /**
     * 获取自定义配置日志过滤器
     *
     * @return
     */
    private static Interceptor getLogInterceptor() {
        HttpLoggingInterceptor logInter = new HttpLoggingInterceptor();
        if (BuildConfig.DEBUG) {
            logInter.setLevel(HttpLoggingInterceptor.Level.BODY);
        } else {
            logInter.setLevel(HttpLoggingInterceptor.Level.BODY);
        }
        return logInter;
    }

    /**
     * 获取自定义配置cookie存储管理
     *
     * @return 管理配置
     */
    private static CookieJar getCookieJar(Context context) {
        return new PersistentCookieJar(new SetCookieCache(), new
                SharedPrefsCookiePersistor(context));
    }

    public static String getUserAgent() {
        String release = Build.VERSION.RELEASE;
        StringBuilder ua = new StringBuilder(BuildConfig.API_HOST);
        ua.append('/' + BuildConfig.VERSION_NAME + '_' + BuildConfig.VERSION_CODE);
        ua.append("/Android");
        ua.append("/").append(release);
        ua.append("/" + "");
        userAgent = ua.toString();
        return userAgent;
    }
}
